﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TMDBAPI;
using IMDBAPI;
using System.IO;
using System.Xml;


namespace Movies
{

    public class MovieDetails
    {

        private static String DEF_HTML_FILE = "MovieDetails.html";
        private static String DEF_COVER_FILE = "MovieCover.jpg";

        private static String OLD_HTML_FILE = "imdb_details.html";
        private static String OLD_COVER_FILE = "imdb_cover.jpg";

        private ImdbMovie imdbMovieDetail = null;
        private TmdbMovie tmdbMovieDetail = null;
        private List<String[]> searchResult = null;

        public MovieDetails(String loadURL)
        {
            LoadLocation = loadURL;
            Load();
        }

        public MovieDetails(ImdbMovie imdbMovie, TmdbMovie tmdbMovie, List<String[]> otherSearchResult)
        {
            updateMovieDetails(imdbMovie, tmdbMovie);
            searchResult = otherSearchResult;
        }


        public MovieDetails(ImdbMovie imdbMovie, TmdbMovie tmdbMovie)
        {
            updateMovieDetails(imdbMovie,tmdbMovie);
        }

        private void updateMovieDetails(ImdbMovie imdbMovie, TmdbMovie tmdbMovie)
        {
            imdbMovieDetail = imdbMovie;
            tmdbMovieDetail = tmdbMovie;

            ImdbID = imdbMovie.ImdbID;
            Name = imdbMovie.Name;
            Year = imdbMovie.Year;
            Rated = imdbMovie.Rated;
            Released = imdbMovie.Released;
            GenreList = imdbMovie.GenreList;
            Director = imdbMovie.Director;
            Writer = imdbMovie.Writer;
            Actors = imdbMovie.Actors;
            Plot = imdbMovie.Plot;
            ImdbCoverURL = imdbMovie.CoverURL;
            Runtime = imdbMovie.Runtime;
            ImdbRating = imdbMovie.Rating;
            ImdbVotes = imdbMovie.Votes;
            Award = imdbMovie.Awards;
            Metascore = imdbMovie.Metascore;

            //AlternativeName = tmdbMovie.AlternativeName;
            //Budget = tmdbMovie.Budget;
            //Countries = tmdbMovie.Countries;
            //TmdbID = tmdbMovie.Id;
            //Language = tmdbMovie.Language;
            //TmdbRating = tmdbMovie.Rating;
            //Revenue = tmdbMovie.Revenue;
            //Studios = tmdbMovie.Studios;
            //Trailer = tmdbMovie.Trailer;
        }

        private void Load()
        {
            loadDetails(this);
            
        }


        public void ClearDetails()
        {
            if (File.Exists(LoadLocation + "/" + DEF_HTML_FILE))
            {
                File.Delete(LoadLocation + "/" + DEF_HTML_FILE);
            }
            if(File.Exists(LoadLocation + "/" + OLD_HTML_FILE))
            {
                File.Delete(LoadLocation + "/" + OLD_HTML_FILE);
            }

            if (File.Exists(LoadLocation + "/" + DEF_COVER_FILE))
            {
                File.Delete(LoadLocation + "/" + DEF_COVER_FILE);
            }

            if (File.Exists(LoadLocation + "/" + OLD_COVER_FILE))
            {
                File.Delete(LoadLocation + "/" + OLD_COVER_FILE);
            }
        }

        

        public void SaveUserDetails()
        {
            if (isSeenStatusChanged)
            {
                if (IsAlreadySeen)
                {
                    hasUpdated = false;
                    DateTime nowDate = DateTime.Now;
                    String dataString = nowDate.Year + "/" + nowDate.Month + "/" + nowDate.Day;
                    HelperDataStoreManager.AddSeenRecord(Name, UserRatting, dataString);
                }
                else
                {
                    hasUpdated = false;
                    HelperDataStoreManager.DeleteSeenRecord(Name);
                }
            }
        }

        private bool isSeenStatusChanged;
        private bool hasUpdated;
        private bool isAlreadySeen = false;
        public bool IsAlreadySeen { 
            get 
            {
                if (!hasUpdated)
                {
                    isAlreadySeen = HelperDataStoreManager.IsExist(Name);
                    hasUpdated = true;
                }
                return isAlreadySeen; 
            }
            set 
            { 
                isAlreadySeen = value; 
                isSeenStatusChanged = true; 
            }
        }
        public String UserRatting { get; set; }
        //public bool IsAlreadySeen { get; set; }

        public bool Save()
        {
            if (DefSaveWithImage)
            {
                return SaveToWithImage(LoadLocation);
            }
            else
            {
                return SaveTo(LoadLocation);
            }
        }

        public bool SaveTo(String location)
        {
            LoadLocation = location;
            try
            {
                File.WriteAllText(LoadLocation + "\\"+OLD_HTML_FILE, GetHTMLContent(this).ToString());
            }
            catch (Exception ex)
            {
                HelperContentProvider.OmitWarning(ex);
                return false;
            }
            return true;
        }


        public bool SaveToWithImage(String location)
        {
            LoadLocation = location;
            bool fileStatus = SaveTo(location);
            if (fileStatus)
            {
                try
                {
                    
                    ImdbMovie imdbMovie = imdbMovieDetail; 
                    if (imdbMovie == null)
                    {
                        imdbMovie = new ImdbMovie();
                        imdbMovie.CoverURL = ImdbCoverURL;
                    }
                    imdbMovie.DownalodCoverAt(LoadLocation + "\\" + OLD_COVER_FILE);
                }
                catch (Exception ex)
                {
                    HelperContentProvider.OmitWarning(ex);
                    return false;
                }
            }
            return (true && fileStatus);
        }

        public List<String[]> SearchResult {
            get {
                return searchResult;
            }
        }

        public string LoadLocation { get; set; }

        public bool DefSaveWithImage { get; set; }

        public string HtmlLocation { get { return LoadLocation + "\\" + OLD_HTML_FILE; } }

        public string LocalCoverLocation { get { return LoadLocation + "\\" + OLD_COVER_FILE; } }

        public string ImdbID { get; set; }

        public string Name { get; set; }

        public string Year { get; set; }

        public string Rated { get; set; }

        public string Released { get; set; }

        public string GenreList { get; set; }

        public string Director { get; set; }

        public string Writer { get; set; }

        public string Actors { get; set; }

        public string Plot { get; set; }

        public string ImdbCoverURL { get; set; }

        public string Runtime { get; set; }

        public string ImdbRating { get; set; }

        public string ImdbVotes { get; set; }

        public string Award { get; set; }

        public string Metascore { get; set; }

        public string AlternativeName { get; set; }

        public string Budget { get; set; }

        public string[] Countries { get; set; }

        public int TmdbID { get; set; }

        public string Language { get; set; }

        public decimal TmdbRating { get; set; }

        public string Revenue { get; set; }

        public string[] Studios { get; set; }

        public string Trailer { get; set; }


        private String correctVote(String vote)
        {
            if (vote != null && !vote.Trim().Equals("N/A") && !vote.Trim().Equals(""))
            {
                for(int len=vote.Length;len<=5;len++)
                {
                    vote = "0" + vote;
                }
            }
            return vote;
        }

        private String correctRuntime(String runtime)
        {
            if (runtime != null && runtime.IndexOf(" hr") == -1 && runtime.IndexOf(" min")>-1)
            {
                runtime = "0 hr " + runtime;
            }
            return runtime;
        }

        private String getActualValue(String value){
            if(value==null){
                return "";
            }
            return value;
        }

        public String[] GetMovieDetailsAsArray()
        {
            String[] retValue = new String[18];
        
            retValue[0] = Name;
            retValue[1] = getActualValue(ImdbRating);
            retValue[2] = correctVote(getActualValue(ImdbVotes));
            retValue[3] = correctRuntime(getActualValue(Runtime));
            retValue[4] = getActualValue(Year);
            retValue[5] = getActualValue(Rated);
            retValue[6] = getActualValue(GenreList);
            retValue[7] = getActualValue(Director);
            retValue[8] = getActualValue(Writer);
            retValue[9] = getActualValue(Actors);
            retValue[10] = getActualValue(Released);
            retValue[11] = getActualValue(Plot);
            retValue[12] = getActualValue(LocalCoverLocation);
            retValue[13] = getActualValue(LoadLocation);
            retValue[14] = getActualValue(HtmlLocation);
            retValue[15] = getActualValue(Metascore);
            retValue[16] = getActualValue(ImdbID);
            retValue[17] = getActualValue(Award);

            return retValue;
        }


        private static String GetHTMLContent(MovieDetails movieDetails)
        {
                StringBuilder htmlTextContent = new StringBuilder();
            
                htmlTextContent = new StringBuilder();
                htmlTextContent.Append("<html>");
                htmlTextContent.Append("\n<head>");
                htmlTextContent.Append("\n    <title>" + movieDetails.Name.Replace("&","&amp;") + "</title>");
                htmlTextContent.Append("\n</head>");
                htmlTextContent.Append("\n<body>");
                htmlTextContent.Append("\n<table width=\"100%\" height=\"100%\">");
                htmlTextContent.Append("\n<tr>");
                htmlTextContent.Append("\n<td align=\"center\" valign=\"middle\">");
                htmlTextContent.Append("\n<table cellpadding=\"5\"><tr><td style=\"border-width:thin;border-style:solid;\">");
                htmlTextContent.Append("\n    <table cellspacing=\"0\" style=\"width:480\">");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td colspan=\"5\" bgcolor=\"black\" align=\"center\" style=\"font-size:20;color:white;text-align:center\"><b>");
                htmlTextContent.Append("\n                " + movieDetails.Name.Replace("&", "&amp;") + "</b></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td style=\"width:60\" valign=\"top\">");
                htmlTextContent.Append("\n                <b>Rating</b></td>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>:</b><rating>" + movieDetails.ImdbRating + "</rating></td>");
                htmlTextContent.Append("\n            <td style=\"width:60\" valign=\"top\">");
                htmlTextContent.Append("\n                <b>Votes</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" style=\"width:150\">");
                htmlTextContent.Append("\n                <b>:</b><votes>" + movieDetails.ImdbVotes + "</votes></td>");
                htmlTextContent.Append("\n            <td rowspan=\"7\" style=\"width:100;text-align:right\" align=\"right\">");
                htmlTextContent.Append("\n                <img id=\"poster\" alt=\"\" src=\"imdb_cover.jpg\" height=\"200\" width=\"150\"/><input type=\"hidden\" id=\"webPoster\" value=\"" + movieDetails.ImdbCoverURL + "\"/></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Rated</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><rated>" + movieDetails.Rated + "</rated></td>");
                htmlTextContent.Append("\n        </tr>");

                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Runtime</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><runtime>" + movieDetails.Runtime + "</runtime></td>");
                htmlTextContent.Append("\n        </tr>");

                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Release</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><released>" + movieDetails.Released + "</released> <span>[</span><year>" + movieDetails.Year + "</year><span>]</span></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Genre</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><genre>" + movieDetails.GenreList.Replace("&", "&amp;") + "</genre></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Director</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><director>" + movieDetails.Director.Replace("&", "&amp;") + "</director></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Writer</b></td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><writer>" + movieDetails.Writer.Replace("&", "&amp;") + "</writer></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Actor</b></td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"4\">");
                htmlTextContent.Append("\n                <b>:</b><actors>" + movieDetails.Actors.Replace("&", "&amp;") + "</actors></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Plot</b></td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"4\" align=\"justify\" style=\"text-align:justify\">");
                htmlTextContent.Append("\n                <b>:</b><plot>" + movieDetails.Plot.Replace("&", "&amp;") + "</plot></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Metascore</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><metascore>" + movieDetails.Metascore + "</metascore></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n        <tr>");
                htmlTextContent.Append("\n            <td valign=\"top\">");
                htmlTextContent.Append("\n                <b>Award</b> </td>");
                htmlTextContent.Append("\n            <td valign=\"top\" colspan=\"3\">");
                htmlTextContent.Append("\n                <b>:</b><award>" + movieDetails.Award + "</award></td>");
                htmlTextContent.Append("\n        </tr>");
                htmlTextContent.Append("\n    </table>");
                htmlTextContent.Append("\n    </td></tr></table>");
                htmlTextContent.Append("\n</td>");
                htmlTextContent.Append("\n</tr>");
                htmlTextContent.Append("\n</table><span style=\"visibility:hidden\"><imdb_title>" + movieDetails.ImdbID + "</imdb_title></span>");
                htmlTextContent.Append("\n</body>");
                htmlTextContent.Append("\n</html>");
            
            return htmlTextContent.ToString();
        }

        private static MovieDetails loadDetails(MovieDetails details)
       {

           if (!File.Exists(details.HtmlLocation))
           {
               String name = HelperNameUtil.NormalizeMovieName(details.LoadLocation);
               details.Name = name;
               return details;
           }

           FileStream reader = new FileStream(details.HtmlLocation, FileMode.Open, FileAccess.Read, FileShare.Read); //Set up the filestream (READER) //
           XmlDocument CompSpecs = new XmlDocument();
           try
           {
               CompSpecs.Load(reader); //Load the data from the file into the XmlDocument (CompSpecs) //
           }
           catch (Exception ex)
           {
               HelperContentProvider.OmitWarning(ex);
               return null;
           }

           details.Name = readElement("title", CompSpecs);
           details.ImdbRating = readElement("rating", CompSpecs);
           details.ImdbVotes = readElement("votes", CompSpecs);
           details.Runtime = readElement("runtime", CompSpecs);
           details.Year = readElement("year", CompSpecs);
           details.Rated = readElement("rated", CompSpecs);
           details.GenreList = readElement("genre", CompSpecs);
           details.Director = readElement("director", CompSpecs);
           details.Writer = readElement("writer", CompSpecs);
           details.Actors = readElement("actors", CompSpecs);
           details.Plot = readElement("plot", CompSpecs);
           details.Released = readElement("released", CompSpecs);
           details.Award = readElement("award", CompSpecs);
           details.Metascore = readElement("metascore", CompSpecs);
           details.ImdbID = readElement("imdb_title", CompSpecs);
           

           reader.Close();

           return details;
        }
        private static String readElement(String elementName,XmlDocument CompSpecs)
        {
            XmlNodeList NodeList = CompSpecs.GetElementsByTagName(elementName); // Create a list of the nodes in the xml file //
            XmlElement element = (XmlElement)NodeList[0];
            
            String eleText = "";
            if (element != null)
            {
                eleText = element.InnerText;
            }
            return eleText;
        }
    }

}
 

